package leetcode.sword;

import java.util.ArrayList;

public class Solution29_ {

    public static void main(String[] args) {
        int[][] matrix = {{1,2,3},{5,6,7},{9,10,11}};
        System.out.println(spiralOrder(matrix));
    }

    public static int[] spiralOrder(int[][] matrix) {
        int rowh = matrix.length;
        if(rowh==0) return new int[0];
        int colh = matrix[0].length;
        if(colh==0) return new int[0];
        ArrayList<Integer> all = new ArrayList<>();
        frame(matrix,0, rowh-1, 0,colh-1, all);
        int[] res = new int[all.size()];
        for (int i = 0; i < all.size(); i++) {
            res[i] = all.get(i);
        }
        return res;
    }

    /**
     * 从[rowl,coll]->[rowl,colh]->[rowh,colh]->[rowh,coll]->[rowl,coll]遍历
     * @param matrix
     * @param rowl
     * @param rowh
     * @param coll
     * @param colh
     * @return
     */
    public static void frame(int[][] matrix, int rowl, int rowh, int coll, int colh, ArrayList<Integer> all) {
        if(rowl>rowh||coll>colh) return;
        //右
        for (int i = coll; i <=colh ; i++) {
            all.add(matrix[rowl][i]);
        }
        //下
        for (int i = rowl+1; i <=rowh ; i++) {
            all.add(matrix[i][colh]);
        }
        //左
        if(rowl+1<=rowh){ //防止回头重新计算
            for (int i = colh-1; i >=coll ; i--) {
                all.add(matrix[rowh][i]);
            }
        }
        //上
        if(coll+1<=colh){
            for (int i = rowh-1; i >rowl ; i--) {
                all.add(matrix[i][coll]);
            }
        }
        //缩圈
        frame(matrix,rowl+1,rowh-1,coll+1,colh-1,all);
    }
}